<?php 
/**
 * TouchBehavior
 * 
 * Usage in model: 
 * 
 * 1) make sure model's $actsAs array contains something like (those keys are
 * default values You don't need to specify)
 * 
 * 'Touch' => array('field' => 'last_access', 'timestamp'=>'Y-m-d H:i:s')
 * 
 * 2) You can call $this->ModelName->touch() or $this->ModelName->touch(3) in
 * controller
 * 
 * 3) this behavior implements beforeSave() callback for updating value of last
 * access field ;)
 */
class TouchBehavior extends ModelBehavior {
    /**
     * Default model settings
     */
    var $defaultSettings = array('field' => 'last_access', 'timestamp' => 'Y-m-d H:i:s');

    /**
     * Prepare model settings
     * 
     * Redefines parent method
     */
    function setup(&$model, $config = array()) {
        $field = $this->defaultSettings['field'];

        if (!empty($config['field'])) {
            $field = $config['field'];
        }

        // conditional initialization of settings for this model
        if ($model->hasField($field)) {
            $timestamp = $this->defaultSettings['timestamp'];
            
            if (!empty($config['timestamp'])) {
                $timestamp = $config['timestamp'];
            }

            $this->settings[$model->name] = array(
                'field' => $field, 
                'timestamp' => $timestamp
            );
        }
    }

    /**
     * Updates only field for last access information
     */
    function touch(&$model, $id = null) {
        if (isset($this->settings[$model->name])) {
            if (!empty($id)) {
                $model->id = $id; 
            }

            if (!empty($model->id)) {
                $field = $this->settings[$model->name]['field'];

                // uses $fieldList argument, so data can be prepared in beforeSave()
                return $model->save(null, false, array($field));
            }
        }
        
        return false;
    }

    /**
     * Modify last access field on every save
     * 
     * Redefines parent method
     */
    function beforeSave(&$model) {
        if (isset($this->settings[$model->name])) {
            $field = $this->settings[$model->name]['field'];
            $timestamp = $this->settings[$model->name]['timestamp'];

            $model->data[$model->name][$field] = date($timestamp);
        }
    }
}
?>